package com.beiming.moudle.auth.controller;


import com.beiming.common.utils.Result;
import com.beiming.common.utils.TokenUtil;
import com.beiming.moudle.auth.entity.utillClass.User;
import com.beiming.moudle.auth.entity.UserEntity;
import com.beiming.moudle.auth.service.UserService;
import com.beiming.moudle.auth.vo.TokenVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 登录校验
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 登录
     *
     * @param
     * @return token登录凭证
     */
    @PostMapping("/login")
    public Result login(@RequestBody User u) {
        System.out.println(u);
        UserEntity user = userService.findByUsername(u.getUsername());
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(u.getPassword())) {
            return Result.build(400, "用户名或密码错误");
        } else {
            //生成token，并保存到数据库
            String token = userService.createToken(user);
            TokenVO tokenVO = new TokenVO();
            tokenVO.setToken(token);
            tokenVO.setUsername(user.getUserName());
            return Result.ok(tokenVO);
        }
    }

    /**
     * 登出
     *
     * @param
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        //从request中取出token
        String token = TokenUtil.getRequestToken(request).get("admin_token").toString();
        userService.logout(token);
        return Result.ok();
    }


    /**
     * 测试
     *
     * @param
     * @return
     */
    @PostMapping("/test")
    public Result test(String token) {
        return Result.ok("恭喜你，验证成功啦，我可以返回数据给你");
    }



}



